class Category < ActiveRecord::Base
  include HeaderTools
    
	acts_as_nested_set
	
	has_many :posts
	belongs_to :page
	
	validates_presence_of :title, :slug
	validates_uniqueness_of :slug
	attr_accessor :mode, :category_id
	
	before_save :apply_mode
	after_save :refresh_tree
	
	named_scope :menu, :conditions=>{:is_menu=>true, :is_visible=>true}, :order=>"position"
	named_scope :links, :conditions=>{:is_menu=>false, :is_visible=>true}, :order=>"position"
	named_scope :dynamic, :conditions=>{:page_id=>nil}, :order=>"title"
	named_scope :root, :conditions=>"parent_id IS NULL OR parent_id = 0"
	
	define_index do
		indexes [:title, :slug], :as => :name
		indexes [page.title, page.content], :as=>:content
  	has :page_id
  end
	
	def before_create
  	#self.parent_id = 0 if self.parent_id.blank?
  end
  
  def after_create
  	 self.parent_category.add_child(self) unless self.parent_category.nil?
  end
   
	def to_param
		slug
	end
	
	def is_static?
		!self.page_id.blank?
	end
	
	def mode
		@mode || 'static'
	end
  
  def make_root
   	self[parent_column] = 0
   	self[root_column] = self.id
   	self[left_col_name] = 1
    self.save
  end
  
  def category_id
  	self.parent_id
  end
  
  def refresh_tree
  	_parent = @category_id.blank? ? nil : self.class.find_by_id(@category_id)
  	return if _parent.nil?
  	self.move_to_child_of(_parent) if !_parent.children.include?(self) && _parent.id != self.id
  end
  
  def parent_category
   	return if self.parent_id.blank? || self.parent_id == 0
   	@parent_category ||= self.class.find(self.parent_id)
   	@parent_category   	
  end
	
	def apply_mode
   	case mode
   		when 'static' then
   			self.create_page(:title=>self.title, :content=>'') if self.page.nil?
   		when 'dynamic' then
   			self.page.destroy if is_static?
   	end
	end
end
